import os
import logging
import asyncio
from typing import Dict, Any
from .interfaces import IVideoProcessor
from .exceptions import VideoProcessingError, FileValidationError
from .types import ProcessingResult
from .encoder import VideoEncoder
from .model import ModelCaller
from config.settings import settings

logger = logging.getLogger(__name__)

class VideoProcessor(IVideoProcessor):
    """视频处理器实现"""
    
    def __init__(
        self,
        encoder: VideoEncoder = None,
        model_caller: ModelCaller = None
    ):
        self.encoder = encoder or VideoEncoder()
        self.model_caller = model_caller or ModelCaller()
    
    async def process_video(
        self, 
        video_path: str, 
        text_prompt: str = "描述这个视频的具体过程"
    ) -> ProcessingResult:
        """处理视频文件并获取AI回复"""
        retry_count = 0
        last_error = None
        
        while retry_count < settings.MAX_RETRIES:
            try:
                # 检查文件是否存在
                if not os.path.exists(video_path):
                    raise FileValidationError(f"视频文件不存在: {video_path}")
                
                # 检查文件大小
                file_size = os.path.getsize(video_path)
                if file_size > settings.MAX_FILE_SIZE:
                    raise FileValidationError(
                        f"视频文件过大，最大支持{settings.MAX_FILE_SIZE/1024/1024}MB"
                    )
                
                # 编码视频文件
                base64_video = self.encoder.encode_video(video_path)
                
                # 调用模型
                result = await self.model_caller.create_completion(
                    base64_video, 
                    text_prompt
                )
                
                return {
                    "success": True,
                    "data": result,
                    "error": None
                }
                
            except Exception as e:
                last_error = e
                retry_count += 1
                if retry_count < settings.MAX_RETRIES:
                    logger.warning(
                        f"处理失败，{settings.RETRY_DELAY}秒后重试 "
                        f"({retry_count}/{settings.MAX_RETRIES}): {str(e)}"
                    )
                    await asyncio.sleep(settings.RETRY_DELAY)
                else:
                    logger.error(f"处理失败，已达到最大重试次数: {str(e)}")
                    return {
                        "success": False,
                        "data": None,
                        "error": str(last_error)
                    } 